import json
from io import StringIO
import os
curpath = os.path.dirname(os.path.abspath(__file__))

json_str = json.load(open(curpath + '/data.json'))
cypher = StringIO()
for k in json_str.keys():
    songname = json_str[k]['songName'][0]
    visitnum = json_str[k]['visitNum'][0]
    cypher_str = f'''merge (n:song {{id:"{k}"}}) on create set n.name="{songname}", n.visitnum="{visitnum}" on match set n.name="{songname}", n.visitnum="{visitnum}";\n'''
    if 'album' in json_str[k]:
        for i in json_str[k]['album']:
            i = i.replace('"','\\"')
            cypher_str += f'''merge (m:album {{name:"{i}"}});\n'''
            cypher_str += f'''match (n:song {{id:"{k}"}}), (m:album {{name:"{i}"}}) merge (n)-[r:belongs]->(m);\n'''
    if 'singer' in json_str[k]:
        for i in json_str[k]['singer']:
            i = i.replace('"','\\"')
            cypher_str += f'''merge (m:singer {{name:"{i}"}});\n'''
            cypher_str += f'''match (n:song {{id:"{k}"}}), (m:singer {{name:"{i}"}}) merge (n)-[r:sangby]->(m);\n'''
    if 'tags' in json_str[k]:
        for i in json_str[k]['tags']:
            i = i.replace('"','\\"')
            cypher_str += f'''merge (m:tag {{name:"{i}"}});\n'''
            cypher_str += f'''match (n:song {{id:"{k}"}}), (m:tag {{name:"{i}"}}) merge (n)-[r:typeof]->(m);\n'''
    cypher.writelines(cypher_str)

with open(curpath + '/graph_songs_cypher.cypher', 'w', encoding='utf-8') as f:
    f.write(cypher.getvalue())